package com.example.synccenter.service;

import com.example.synccenter.entity.IdentitySourceEntity;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.example.synccenter.dingtalk.DingTalkConfig;
import com.example.synccenter.feishu.FeishuConfig;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * 身份源配置验证服务，提供对不同类型身份源配置的验证功能。
 * 支持钉钉和飞书等身份源的配置格式验证。
 */
@Service
@RequiredArgsConstructor
public class IdentitySourceValidationService {
    
    private final ObjectMapper objectMapper;
    
    /**
     * 验证身份源配置
     * @param entity 身份源实体
     * @throws IllegalArgumentException 当配置验证失败时抛出
     */
    public void validateConfig(IdentitySourceEntity entity) {
        // 验证基本字段
        if (StringUtils.isBlank(entity.getType())) {
            throw new IllegalArgumentException("身份源类型不能为空");
        }
        if (StringUtils.isBlank(entity.getCode())) {
            throw new IllegalArgumentException("身份源编码不能为空");
        }
        if (StringUtils.isBlank(entity.getName())) {
            throw new IllegalArgumentException("身份源名称不能为空");
        }
        if (StringUtils.isBlank(entity.getConfig())) {
            throw new IllegalArgumentException("身份源配置不能为空");
        }
        
        // 验证配置格式
        try {
            switch (entity.getType()) {
                case "DINGTALK":
                    validateDingTalkConfig(entity.getConfig());
                    break;
                case "FEISHU":
                    validateFeishuConfig(entity.getConfig());
                    break;
                default:
                    throw new IllegalArgumentException("不支持的身份源类型: " + entity.getType());
            }
        } catch (Exception e) {
            throw new IllegalArgumentException("配置格式验证失败: " + e.getMessage());
        }
    }
    
    /**
     * 验证钉钉配置格式
     * @param config 配置JSON字符串
     * @throws Exception 当配置格式无效或缺少必要字段时抛出
     */
    private void validateDingTalkConfig(String config) throws Exception {
        DingTalkConfig dingTalkConfig = objectMapper.readValue(config, DingTalkConfig.class);
        if (StringUtils.isBlank(dingTalkConfig.getUrl())) {
            throw new IllegalArgumentException("钉钉配置URL不能为空");
        }
    }
    
    /**
     * 验证飞书配置格式
     * @param config 配置JSON字符串
     * @throws Exception 当配置格式无效或缺少必要字段时抛出
     */
    private void validateFeishuConfig(String config) throws Exception {
        FeishuConfig feishuConfig = objectMapper.readValue(config, FeishuConfig.class);
        if (StringUtils.isBlank(feishuConfig.getUrl())) {
            throw new IllegalArgumentException("飞书配置URL不能为空");
        }
    }
} 